package cn.yangliu.shiro.web;

import cn.yangliu.comm.entity.swagger.JsonResult;
import cn.yangliu.comm.tools.WebUtils;
import cn.yangliu.shiro.ShiroWebUtils;
import cn.yangliu.shiro.config.ShiroProperties;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ShiroLogoutController extends AbstractController {

    @Autowired
    private ShiroProperties shiroProperties;

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logout();
        if (WebUtils.checkJsonAjax()) {
            JsonResult result = new JsonResult();
            result.setMsg("退出成功");
            WebUtils.printData(result, response);
        }
        return new ModelAndView("redirect:" + shiroProperties.getLoginUrl());
    }

    private void logout() {
        Session session = ShiroWebUtils.getSession();
        session.setTimeout(0L);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }
}
